<?php
namespace app\admin\controller;

use app\admin\model\ArticleModel;
use app\common\helper\Uploader;
use app\common\model\data\SystemMusicSpiderModel;
use app\common\model\project_model\SystemMusicModel;
use think\Controller;
use think\Db;
use think\Exception;

/**
 * qq音乐拔取控制器
 * Class Spider
 * @package app\bea\controller
 */
class SystemMusicSpider extends Controller
{
    /**
     * qq音乐查询list拔取数据
     *
     * @return \think\response\Json
     */
    public function qq_list_add() {
        if ($this->request->isPost()) {
            $page_num = input('page_num/d', 5);
            $keyword = input('keyword', '');
            if (empty($keyword)) {
                return json(['code' => 0, 'error' => '请输入搜索关键字']);
            }
            Db::startTrans();
            try {
                $ch =curl_init();
                $url = sprintf(SystemMusicSpiderModel::QQ_API_MUSIC_SEARCH,$page_num, urlencode($keyword));
                curl_setopt($ch,CURLOPT_URL,$url);
                //curl_setopt($ch,CURLOPT_,true);
                curl_setopt($ch,CURLOPT_POST,false);
                //curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
                curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
                //curl_setopt($ch,CURLOPT_HEADER,true);
                //curl_setopt($ch,CURLOPT_HTTPHEADER,$header);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
                //curl_setopt($ch,CURLOPT_COOKIE,$app_key);

                $content = curl_exec($ch);
                $err = curl_errno($ch);
                if ($err) {
                    return json(['code' => 0, 'error' => '首页抓取失败:' . $err]);
                }
                $data = json_decode($content,true);
                $list = $data['data']['song']['list'];
                curl_close($ch);

                // 获取详情数据并格式化
                $data = $this->formatSearchData($list);
                $model = new SystemMusicModel();
                $res = $model->allowField(true)->saveAll($data);
                if (!$res) {
                    throw new Exception('插入数据库失败');
                }
                Db::commit();
                return json(['code' => 1, 'msg' => 'success']);
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 0, 'error' => $e->getMessage()]);
            }
        } else {

            //$this->assign('tag_list', $tag_list);
            return $this->fetch('system_music_spider/qq_list_add');
        }
    }



    /**
     * 格式化qq音乐搜索的list数据
     *
     * @param $data
     * @return array
     * @throws \Exception
     */
    private function formatSearchData($data) {
        $insert = [];
        foreach ($data as $item) {
            $insert[] = [
                'music_id' => $item['mid']?$item['mid']:$item['file']['media_mid'],
                'created_time' => date('Y-m-d H:i:s', time()),
                'song_id' => $item['id'],
                'lyric' => $item['lyric'],
                'title' => $item['name'],
                'singer' => $item['singer'][0]['name'],
                'time_public' => $item['time_public'],
                'g_uid' => mt_rand(1000, rand(10000000000, 99999999999)),
            ];
        }
        return $insert;
    }
}